<template>
    <div class="report-management-container">
        <el-card shadow="never">
            <!-- 头部区域 -->
            <template #header>
                <div class="card-header">
                    <span class="header-title">报工单管理</span>
                </div>
            </template>

            <!-- 搜索和操作区域 -->
            <div class="search-operation-area">
                <!-- 搜索表单 -->
                <el-form :model="formData" ref="formRef" label-width="90px" :inline="true" class="search-form">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="任务编号" prop="taskId">
                                <el-input v-model="formData.taskId" placeholder="请输入任务编号" size="large" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="产品编号" prop="materialName">
                                <el-input v-model="formData.materialName" placeholder="请输入产品物料编号" size="large" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="报工人ID" prop="reportPeopleId">
                                <el-input v-model="formData.reportPeopleId" placeholder="请输入报工人" size="large"
                                    clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="质检员ID" prop="checkId">
                                <el-input v-model="formData.checkId" placeholder="请输入质检员" size="large" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="padding-left: 50px;">
                            <el-form-item>
                                <!-- 搜索和重置按钮 -->
                                <el-button type="primary" @click="handleSearch">搜索</el-button>
                                <el-button type="info" :plain=true @click="resetForm">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 操作按钮区域 -->
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-button @click="toInsert" type="primary" :plain="true">+添加</el-button>
                        <el-button type="success" :plain="true" :disabled="selectedRows.length !== 1"
                            @click="handleUpdate(selectedRows[0])">修改</el-button>
                        <el-button type="danger" :plain="true" :disabled="!selectedRows.length" 
                            @click="handleBatchDelete">删除</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 数据表格 -->
            <el-table :data="tableData.records" style="width: 100%" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="报工编号" prop="reportCode" width="150" fixed>
                    <template #default="{ row }">
                        <el-link type="primary" @click.stop="openDetailDialog(row)">
                            {{ row.reportCode }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column label="生产计划ID" prop="productionPlanId" width="150" />
                <el-table-column label="生产任务ID" prop="taskId" width="150" />
                <el-table-column label="产品编号" prop="materialId" width="120" />
                <el-table-column label="产品名称" prop="materialName" width="120" />
                <el-table-column label="产品规格" prop="specificationsAndModels" width="120" />
                <el-table-column label="报工人ID" prop="reportPeopleId" width="120" />
                <el-table-column label="报工日期" prop="reportTime" width="120" />
                <el-table-column label="报工状态" prop="status" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="总报工数量" prop="totalQuantity" width="120" align="right" />
                <el-table-column label="质检员ID" prop="checkId" width="120" />


                <el-table-column label="操作" width="180" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click.stop="handleUpdate(row)" v-if="row.status ===0 ">
                            修改
                        </el-button>
                        <el-button type="success" size="small" @click.stop="handle(row)" v-if="row.status !==0 ">
                            查看
                        </el-button>
                        <el-button type="danger" size="small" @click.stop="handleDelete(row)" v-if="row.status === 0">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination @current-change="loadData" v-model:currentPage="tableData.current"
                :page-sizes="[2, 4, 6, 8, 10]" :page-size="tableData.size" :total="tableData.total" background>
            </el-pagination>


            <!-- 表单弹窗 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" :destroy-on-close="true"
                @closed="handleDialogClosed">
                <router-view @ref-table="refTable" :data="data"></router-view>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import request from '@/api/request'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 加载数据
let data = ref([])

// 弹窗控制
let refTable = () => {
    dialogVisible.value = false
}

// 搜索表单数据
const formData = ref({
    taskId: '',
    materialName: '',
    reportPeopleId: '',
    checkId: '',

})

// 分页数据
const tableData = ref({
    current: 1,    // 当前页码
    size: 5,      // 每页显示条数
    total: 0,      // 总条数
    records: []    // 当前页数据
})

// 批量删除数据
const deleteData=ref([])

const loadData = () => {
    const params = {
        current: tableData.value.current,
        size: tableData.value.size,
        ...formData.value
    }
    request({
        url: "/report/page",
        method: "get",
        params
    }).then(res => {
        tableData.value = res.data
        console.log(tableData.value)
    })
}

loadData()

// 选中行数据
const selectedRows = ref([])
const currentRow = ref(null)

// 弹窗控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogKey = ref(0)
const formRef = ref(null)

const StatusType = ref([
    { value: 0, label: '未确认' },
    { value: 1, label: '已确认' },
    { value: 2, label: '已完成' }
])


// 状态类型映射
const getStatusType = (status) => {
    const map = {0: 'danger',1: 'success',2:"warning" }
    return map[status] || 'info'
}

const getStatusText = (status) => {
    const map = { 0:'未确认',1: '已确认',2:"已完成" }
    return map[status] || '未知状态'
}

// 搜索
const handleSearch = () => {
    tableData.value.current = 1
    console.log(formData.value)
    loadData()
}
// 重置表单
const resetForm = () => {
    formRef.value?.resetFields()
    handleSearch()
}

// 处理行选中
const handleSelectionChange = (val) => {
    selectedRows.value = val
}

//查看详情
let openDetailDialog = (row) => {
    dialogTitle.value = "报工单信息"
    data.value = row
    console.log(data.value.reportId)
    dialogVisible.value = true
    router.push("/production/report/list")
}

// 添加报工单
const toInsert = () => {
    dialogTitle.value = "新增报工单"
    currentRow.value = null
    dialogKey.value++
    dialogVisible.value = true
    router.push('/production/report/insert')
}

// 修改报工单
const handleUpdate = (row) => {
    if (!row) return
    dialogTitle.value = "修改报工单"
    data.value = row
    dialogVisible.value = true
    router.push('/production/report/update')
}

//查看
const handle = (row) => {
    if (!row) return
    dialogTitle.value = "报工单信息"
    data.value = row
    dialogVisible.value = true
    router.push('/production/report/update')
}

// 删除单条数据
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除报工单【${row.reportCode}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
       if (row.status != 0) {
            ElMessage.error('该计划已开始生产，不能删除')
            return
        }
        request({
            url: `/report/deleteReport/`+row.reportId,
            method: 'delete',
            params: { reportId: row.reportId }
        }).then(() => {
            console.log(row.reportId)
            ElMessage.success('删除成功')
            loadData()  // 重新加载数据
            if (currentRow.value && currentRow.value.reportId === row.reportId) {
                currentRow.value = null
            }
        })
    })
}

// 批量删除
const handleBatchDelete = () => {
    if (!selectedRows.value.length) return


     // 检查是否有已完成的领料单
    const completedOrders = selectedRows.value.filter(item => item.status === 2 || 1)
    if (completedOrders.length > 0) {
        ElMessage.warning('包含已完成的报工单，不能删除')
        return
    }


    const reportNos = selectedRows.value.map(item => item.reportCode).join('、')
    ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条报工单吗?<br>${reportNos}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
    }).then(() => {
        const ids = selectedRows.value.map(item => item.reportId)
        deleteData.value = deleteData.value.filter(item => !ids.includes(item.reportId))
        console.log(deleteData.value)
        request({
            url: `/report/batchDelete`,
            method: 'put',
            data: selectedRows.value
        }).then(() => {
            // 重新加载数据
            loadData()
        })
        selectedRows.value = []
        ElMessage.success('删除成功')
    }).catch(() => {
        // 取消删除
    })
}

// 处理弹窗关闭
const handleDialogClosed = () => {
    loadData()
    router.push('/production/report')
}

</script>

<style scoped>
.report-management-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
}

.header-title {
    font-size: 18px;
    font-weight: bold;
    color: var(--el-text-color-primary);
}

.search-operation-area {
    margin-bottom: 20px;
}

.search-form {
    margin-bottom: 15px;
}

.action-buttons {
    margin-bottom: 15px;
}

.el-table {
    margin-top: 15px;
}

.el-tag {
    margin: 2px;
}
</style>